import org.json.JSONObject;

import java.io.*;
import java.net.*;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.DataFormatException;


public class getSeat {


    public static void main(String[] args) throws Exception {
        soutInfos();
        Map<String, String> settings = getSettings("./settings.txt");

        File file = new File("./librarySeatInfos.csv");



        CookieManager manager = new CookieManager();
        manager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
        CookieHandler.setDefault(manager);


        System.out.println("您的登录账号为："+settings.get("学号"));
//        System.out.println(settings.get("密码"));
        System.out.println("您的首选座位为："+settings.get("首选座位"));
        System.out.println("您的备选座位为："+settings.get("备选座位"));
        System.out.println("您的预约开始时间为："+settings.get("预约开始时间"));
        System.out.println("您的预约结束时间为："+settings.get("预约结束时间"));


        List<String> loginInfos = Login(settings.get("学号"), settings.get("密码"));


        String data = loginInfos.get(1);

//        System.out.println(data);
        String seat1 = settings.get("首选座位");
        String seat2 = settings.get("备选座位");
        String StartTime = settings.get("预约开始时间");
        String EndTime = settings.get("预约结束时间");
        seat1 = getSeatCodeByFormData(seat1);

        seat2 = getSeatCodeByFormData(seat2);

        String s1 = formatDate(StartTime);

        String s2 = formatDate(EndTime);
        if (data != null) {
            JSONObject json = new JSONObject(data);
            JSONObject jsonObj = json.getJSONObject("data");//获取json数组中的data项

            String cookies = loginInfos.get(0);
//            cookies = cookies.substring(cookies.indexOf("=")+1,cookies.indexOf(";"));

            if(json.getInt("ret")==1){

              String userName = jsonObj.getString("name");

                System.out.println("登录成功");
                System.out.println("用户名称："+userName);
                String s = reserveSeat(seat1, s1, s2);

//                printCookie(manager.getCookieStore());


                JSONObject reserveJson = new JSONObject(s);
                int reserveAns = reserveJson.getInt("ret");//获取json数组中的data项
                if(reserveAns == 1 ){
                    System.out.println("预约首选座位成功");
                }
                else{
                    String spare_s = reserveSeat(seat2, s1, s2);
                    JSONObject reserveSpareJson = new JSONObject(spare_s);
                    int reserveSpareAns = reserveSpareJson.getInt("ret");//获取json数组中的data项
                    if(reserveSpareAns == 1 ){
                        System.out.println("次选首选座位成功");
                    }
                    else {

                        System.out.println(reserveSpareJson.getString("msg"));
                        System.out.println("抱歉，预约失败！");
                    }
                }


            }
            else {
                System.out.println("抱歉，请检查您的用户名密码");
            }
        }
        else {
            System.out.println("服务器正忙，请稍后再试");
        }
        Scanner input = new Scanner(System.in);
        String Y_N = input.nextLine();



    }

    private static String reserveSeat(String seat1, String s1, String s2) {

        String result = "";
        BufferedReader in = null;
        try {
            String firstSeatString = "http://10.21.95.57/ClientWeb/pro/ajax/reserve.aspx?dev_id="+seat1+"&type=dev&start="+s1+"&end="+s2+"&act=set_resv";


            URL realUrl = new URL(firstSeatString);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

//            connection.setRequestProperty("Set-Cookie",
//                    "ASP.NET_SessionId=+"+cookies+"; path=/; HttpOnly");
            // 建立实际的连接
            connection.connect();


            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"utf8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    public static Map<String,String> getSettings(String file) throws IOException {
        Map<String, String> settingMap = new LinkedHashMap<String, String>();
        File settingFile = new File(file);
        String str;

        try {
            InputStreamReader ir = new InputStreamReader(new FileInputStream(file), "utf8");
            BufferedReader bf = new BufferedReader(ir);

            while ((str = (bf.readLine()))!= null) {
                System.out.println(str);
                if (str.contains("=")) {
                    String[] split = str.split("=");
                    settingMap.put(split[0], split[1]);
                }
            }

        } catch (FileNotFoundException e) {

            System.out.println("抱歉，配置文件没有被找到，请检查相关文件路径是否填写正确");
            Scanner input = new Scanner(System.in);
            String Y_N = input.nextLine();

        } catch (IOException e) {
            System.out.println("抱歉出现未知错误，请稍后再试");
            Scanner input = new Scanner(System.in);
            String Y_N = input.nextLine();
        }
        return settingMap;
    }


    public static List<String> Login(String username,String password) {
        List<String> strings = new ArrayList<>();
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = "http://10.21.95.57/ClientWeb/pro/ajax/login.aspx?act=login&id="+username+"&pwd="+password;

            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            String cookie ="default";

            strings.add(cookie);
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"utf8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            strings.add(result);

        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return strings;
    }





    /**
     *
     * @param seatPosition
     *         座位的位置
     * @Author  DirtyLily
     *          张峻杰
     * @return
     *        座位编码
     */

    public static String getSeatCodeByFormData(String seatPosition) throws Exception {
        String line = "";

        String id = "-1";


        boolean isBoxue = seatPosition.contains("-");
        File cf = new File("./librarySeatInfos.csv");


        FileInputStream inputStream = new FileInputStream(cf);

        BufferedReader infoReader = new BufferedReader(new InputStreamReader(inputStream,"GBK"));
        while ((line = infoReader.readLine()) != null) {
            if(line.contains(seatPosition)){
                boolean flag =  line.contains("-");



                String[] split = line.split(",");
                String s = split[0];
                if(seatPosition.contains(s)) {
                    id = split[1];
                }
            }
        }
        if(id.equals("-1")){
            System.out.println("抱歉，您输入的座位号有误，请退出程序，重新输入");
            Scanner input = new Scanner(System.in);
            String Y_N = input.nextLine();
            throw new Exception("抱歉，您输入的座位号有误，请退出程序，重新输入");
        }
        return id;
    }

    public static String getSeatCode(String seatPosition) throws Exception {
        String seatId = "";
        if(!seatPosition.contains("F")){
            System.out.println("您输入的座位号有误，请退出程序，重新输入");
            Scanner input = new Scanner(System.in);
            String Y_N = input.nextLine();
            throw new Exception("您输入的座位号有误，请重新输入");
        }
        String[] seatInfo = seatPosition.split("F");
        Long floor = Long.parseLong(seatInfo[0]);
        Long seat = Long.parseLong(seatInfo[1]);
        if(floor == 2l){
            if(seat >=1 && seat<=166){
                Long tmp = seat+100455727-1;
                 seatId = tmp.toString();
            }
            else {
                Long tmp = seat+114459838 -167;
               seatId = tmp.toString();
            }
        }
        if(floor == 3l){
            if(seat >=1 && seat<=250){
                Long tmp = seat + 100455893 -1;
                seatId = tmp.toString();
            }
            else if(seat>=251 && seat <= 354){
                Long tmp = seat + 114459895 -251;

            }
            else {
                Long tmp = seat + 114465249 -355;
                seatId = tmp.toString();
            }
        }
        if(floor == 4l){
            if(seat >=1 && seat<=4){
                Long tmp = seat + 114461055 -1;
                seatId = tmp.toString();
            }
            else if(seat>=5 && seat <= 282){
                Long tmp = seat + 100456151 -5;
                seatId = tmp.toString();
            }
            else if(seat>=283 && seat <= 288){
                Long tmp = seat + 100457463 - 283;
                seatId = tmp.toString();
            }
            else if(seat>=289 && seat <= 306){
                Long tmp = seat + + 114459999 -289;
                seatId = tmp.toString();
            }
            else {
                Long tmp = seat + 114464373 -307;
                seatId = tmp.toString();
            }
        }
        if(floor == 5l){
            if(seat >=1 && seat<=166){
                Long tmp = seat + 100456429 - 1;
                seatId = tmp.toString();
            }
            else if(seat>=167 && seat <= 170){
                Long tmp = seat  + 114465126 -167;
                seatId = tmp.toString();


            }

        }
        return seatId;
    }

    public static String formatDate(String Time) throws DataFormatException {


        //解析时间信息
        Pattern datePattern =Pattern.compile("([0-1]{1}[0-9]{1}|[2][0-3]|[7-9]{1}):[0-5]{1}[0-9]{1}");

       Matcher matcher = datePattern.matcher(Time);

       if(!matcher.find()){
           System.out.println("抱歉您输入的日期信息有误，请退出程序重新输入");
           Scanner input = new Scanner(System.in);
           String Y_N = input.nextLine();
           throw new DataFormatException("抱歉您输入的日期信息有误");
       }

        String[] split = Time.split(":");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd+HH:mm");
        Date date=new Date();//取时间
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);

        calendar.add(calendar.DATE,1);

        calendar.set(Calendar.HOUR_OF_DAY,Integer.parseInt(split[0]));
        calendar.set(Calendar.MINUTE,Integer.parseInt(split[1]));
        calendar.set(Calendar.SECOND,0);
        //把日期往后增加一天.整数往后推,负数往前移动
        date = calendar.getTime();

//        Instant instant = date.toInstant();
//
//        ZoneId zoneId = ZoneId.systemDefault();
//
//        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
        String format = df.format(date);
        return format;
    }

    public static void soutInfos(){
        System.out.println("此程序仅用于技术学习，禁止用于任何非法用途。");
        System.out.println("作者：DirtyLily 脏丽丽、Burger 伯格");
        System.out.println("如出现使用问题，请阅读文件中自带的文档！");
        System.out.println("各位勤奋的同学们！加油！！");
    }



    }
